#define _CRT_SECURE_NO_WARNINGS 1
#include "SLTlist.h"



SLTnode* SLTBuySLTnode(SLTdatatype x)
{
	SLTnode* new = (SLTnode*)malloc(sizeof(SLTnode));
	if (new == NULL)
	{
		perror("malloc new");
		exit(-1);
	}

	new->data = x;
	new->next = NULL;

	return new;
}

SLTnode* CreateSLT(int n)
{
	SLTnode* phead = NULL;
	SLTnode* ptmp = NULL;
	int i = 0;
	for (i = 0; i < n; i++)
	{
		SLTnode* n = SLTBuySLTnode(i);
		if (phead == NULL)
		{
			phead = ptmp = n;
		}
		else
		{
			ptmp->next = n;
			ptmp = ptmp->next;
		}
	}
	return phead;
}

void SLTpushback(SLTnode** pps, SLTdatatype x)
{
	SLTnode* new = SLTBuySLTnode(x);
	if (*pps == NULL)
	{
		*pps = new;
	}
	else 
	{
		SLTnode* end = *pps;
		while (end->next)
		{
			end = end->next;
		}
		end->next = new;
	}
}

void SLTprint(SLTnode* ps)
{
	SLTnode* end = ps;
	while (end)
	{
		printf("%d ", end->data);
		end = end->next;
	}
	printf("\n");
}

void SLTpopback(SLTnode** pps)
{
	assert(*pps);
	if ((*pps)->next == NULL)
	{
		free(*pps);
		*pps = NULL;	
	}
	else
	{
		SLTnode* end = *pps;
		SLTnode* tmp = NULL;
		while (end->next)
		{
			tmp = end;
			end = end->next;
		}
		free(end);
		tmp->next = NULL;
	}
	

}

void SLTpushfront(SLTnode** pps, SLTdatatype x)
{
	SLTnode* new = SLTBuySLTnode(x);
	new->next = *pps;
	*pps = new;
}

void SLTpopfront(SLTnode** pps)
{
	assert(*pps);
	SLTnode* end = *pps;
	*pps = end->next;
	free(end);
}


SLTnode* SLTfind(SLTnode* ps, SLTdatatype x)
{
	SLTnode* tmp = ps;
	while (tmp)
	{
		if (tmp->data == x)
		{
			return tmp;
		}
		tmp = tmp->next;
	}
	return NULL;
}


void SLTinsertafter(SLTnode* pos, SLTdatatype x)
{
	assert(pos);
	SLTnode* new = SLTBuySLTnode(x);
	new->next = pos->next;
	pos->next = new;
}


void SLTeraseafter(SLTnode* pos)
{
	assert(pos);
	if (pos->next == NULL)
	{
		return;
	}
	else
	{
		SLTnode* tmp = pos->next;
		pos->next = tmp->next;
		free(tmp);
	}
}


void SLTinsert(SLTnode** pps, SLTnode* pos, SLTdatatype x)
{
	assert(*pps);
	assert(pos);
	SLTnode* new = SLTBuySLTnode(x);
	SLTnode* end = *pps;
	SLTnode* begin = NULL;
	if (*pps == pos)
	{
		new->next = *pps;
		*pps = new;
	}
	else
	{
		while (end != pos)
		{
			begin = end;
			end = end->next;
		}
		begin->next = new;
		new->next = end;
	}
}

void SLTerase(SLTnode** pps, SLTnode* pos)
{
	assert(*pps);
	assert(pos);
	SLTnode* end = *pps;
	SLTnode* begin = NULL;
	if (*pps == pos)
	{
		*pps = NULL;
	}
	else
	{
		while (end != pos)
		{
			begin = end;
			end = end->next;
		}
		begin->next = end->next;
	}

}


void SLTdestroy(SLTnode** pps)
{
	SLTnode* end = *pps;
	while(end)
	{
		SLTnode* next = end->next;
		free(end);
		end = next;
	}
	*pps = NULL;
}